<template>
  <main-content
    title="会员等级"
    :inner-padding="false"
    class="category-main-content"
  >
    <l-r-content v-loading="loading">
      <template #title>
        <div class="side-title-inner">
          等级列表
          <el-button
            v-has="['10100101']"
            type="primary"
            @click="createRank(null)"
          >
            <el-icon>
              <Plus />
            </el-icon>
            <span style="margin-left: 10px">新增会员等级</span>
          </el-button>
        </div>
      </template>

      <template #side-content>
        <extendable-list-item
          v-for="item in rankList"
          class="category-item"
          :width="200"
          :active="selectedRankItem.id === item.id"
          @click="clickRankItem(item)"
        >
          <div class="rank-item">
            <div class="left">
              <el-image
                fit="contain"
                style="width: 45px;height: 45px"
                :src="item.memberLogo"
              />
            </div>
            <div class="right">
              <div class="name">
                {{ item.memberName }}
              </div>
              <div class="desc">
                {{ item.levelDescription }}
              </div>
            </div>
          </div>

          <div
            v-if="item.memberLevel_cn"
            class="corner-label"
          >
            <span class="iconfont icon-huiyuan" /><span>{{ item.memberLevel_cn }}</span>
          </div>

          <template
            #extend-content
            v-has="['10100101','10100102','10100103']"
          >
            <!--            <el-button link type="primary" @click="createRank(item)" v-has="['10100101']">新增</el-button>-->
            <el-button
              v-has="['10100102']"
              link
              type="primary"
              @click="editRank(item)"
            >
              编辑
            </el-button>
            <el-button
              v-has="['10100103']"
              link
              type="danger"
              @click="_deleteRank(item)"
            >
              删除
            </el-button>
          </template>
        </extendable-list-item>
      </template>

      <main-content-tab-bar-wrapper>
        <el-tabs v-model="activePageTabName">
          <el-tab-pane
            v-for="(item, index) in pageTabsList"
            :key="index"
            :label="item.label"
            :name="item.value"
          />
        </el-tabs>
      </main-content-tab-bar-wrapper>

      <template v-if="activePageTabName === 'RankBenefit'">
        <rank-benefit :selected-rank="selectedRankItem" />
      </template>
      <template v-else-if="activePageTabName === 'RankTask'">
        <rank-task :selected-rank="selectedRankItem" />
      </template>
      <template v-else-if="activePageTabName === 'RankUsers'">
        <rank-users :selected-rank="selectedRankItem" />
      </template>
      <template v-else>
        <el-button
          type="primary"
          :icon="TopRight"
        >
          <el-icon />
          打开页面
        </el-button>
      </template>
    </l-r-content>

    <vip-rank-edit-dialog
      v-model:show="isShowVipRankEditDialog"
      :mode="editDialogMode"
      :row-data="operatingRow"
      :rank-list="rankList"
      @done="_getVipRank()"
    />
  </main-content>
</template>
<script lang="ts">
export default {
  name: 'RankList'
}
</script>
<script lang="ts" setup>
import {Ref} from "vue";
import RankUsers from "@/views/vipCenter/RankUsers.vue"
import RankTask from "@/views/vipCenter/RankTask.vue"
import RankBenefit from "@/views/vipCenter/RankBenefit.vue"
import {deleteVipRank, getRankUsers, getVipRank} from "@/api/vipCenter";
import {IRankItem} from "@/api/modules/vipCenter";
import VipRankEditDialog from "@/views/vipCenter/components/VipRankEditDialog.vue";
import {Position, TopRight} from "@element-plus/icons-vue";
import {ElMessageBox} from "element-plus";
import { async } from '@antv/x6/lib/registry/marker/async';
import {toChineseNumber} from "@/utils";

const pageTabsList = ref<{ label: string, value: string }[]>([{
  label: '等级权益',
  value: 'RankBenefit',
}, {
  label: '等级任务',
  value: 'RankTask',
}, {
  label: '等级会员',
  value: 'RankUsers',
},
//   {
//   label: '等级界面',
//   value: 'RankInterface',
// }
])
const activePageTabName = ref('RankBenefit')

// 会员等级列表查询
const loading = ref(false)
const rankList:Ref<IRankItem[]> = ref([])
const _getVipRank = async () => {
  loading.value = true
  const rs = await getVipRank()
  loading.value = false

  if (rs.code === 200) {
    rankList.value = (rs.payload ?? []).map(item => ({
      ...item,
      memberLevel_cn: item.memberLevel !== undefined && item.memberLevel !== null ? toChineseNumber(item.memberLevel) + "级" : ""
    }))
  }
}

const operatingRow: Ref = ref()
const editDialogMode: Ref<'edit' | 'create'> = ref('edit')

// 会员等级列表选中
const selectedRankItem: Ref<IRankItem> = ref<IRankItem>({} as any)
const clickRankItem = (data: IRankItem) => {
  selectedRankItem.value = data
}

// 新增会员等级
const isShowVipRankEditDialog: Ref<boolean> = ref(false)
const createRank = (rowData: IRankItem) => {
  editDialogMode.value = 'create'
  isShowVipRankEditDialog.value = true
  if (!rowData) {
    operatingRow.value = rankList.value?.[rankList.value.length - 1] ?? null
  } else {
    operatingRow.value = rowData
  }
}

// 编辑会员等级
const editRank = (rowData: IRankItem) => {
  editDialogMode.value = 'edit'
  isShowVipRankEditDialog.value = true
  operatingRow.value = rowData
}

// 获取当前会员等级下的会员列表, 仅用于校验该等级下是否有会员
const _getRankUsers = (rowData: IRankItem) => {
  return getRankUsers({gradleId: rowData.id, currentPage: 1, showCount: 10})
}

// 删除会员等级
const _deleteRank = async (rowData: IRankItem) => {
  const rs = await _getRankUsers(rowData)
  if (rs.page?.totalResult) {
    ElMessageBox.confirm('当前会员等级下已有会员，确认删除？', '警告').then(async () => {
      const rs = await deleteVipRank({id: rowData.id, name: rowData.memberName})
      if (rs.code === 200) {
        ElMessage.success('删除成功')
        await _getVipRank()
      }
    })
  } else {
    ElMessageBox.confirm('确认删除此会员等级？', '提示').then(async () => {
      const rs = await deleteVipRank({id: rowData.id, name: rowData.memberName})
      if (rs.code === 200) {
        ElMessage.success('删除成功')
        await _getVipRank()
      }
    })
  }
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  async () => {
    await _getVipRank()
    if (rankList.value.length > 0) {
      clickRankItem(selectedRankItem.value)
    }
  },
  {
    deep: true
  }
)

onMounted(async () => {
  await _getVipRank()
  if (rankList.value.length > 0) {
    clickRankItem(rankList.value[0])
  }
})

</script>

<style scoped lang="scss">
.side-title-inner {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.category-item {
  margin-top: 6px;
  position: relative;

  .rank-item {
    display: flex;
    align-items: center;

    .name {
      font-size: 16px;
      color: var(--el-color-primary);
      margin-bottom: 5px;
    }

    .desc {
      font-size: 12px;
      color: var(--el-color-info-dark-2);
    }
  }

  .left {
    width: 50px;
    height: 50px;
    margin-right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #eee;
    overflow: hidden;
    border-radius: 5px;
  }

  .right {
    flex: 1;
  }

  .corner-label {
    position: absolute;
    right: 0;
    top: 0;
    background: var(--el-color-primary);
    padding: 3px 10px;
    font-size: 12px;
    color: white;
    border-bottom-left-radius: 10px;
    transform: scale(0.8);
    transform-origin: top right;
    display: flex;
    align-items: center;

    .iconfont {
      margin-right: 5px;
    }
  }
}

:deep(.main-content-tab-bar-wrapper) {
  margin-bottom: 0;
}

</style>
